//
//  ImagesDetailController.m
//  Product_NEWS
//
//  Created by dllo on 16/1/8.
//  Copyright © 2016年 FCH. All rights reserved.
//

#import "ImagesDetailController.h"
#import "ImagesDetailModel.h"
#import "ImageDetailView.h"
#import "IndexScrollView.h"
#import "NetRequest.h"
#import "HeadLineViewController.h"
#import "UMSocialSnsPlatformManager.h"
#import "UMSocialSnsService.h"
#import "CommentController.h"
@interface ImagesDetailController ()<UIScrollViewDelegate,UIAlertViewDelegate>
@property (nonatomic, retain) ImageDetailView *detailView;
@property (nonatomic, retain) NSMutableArray *photosData;
@property (nonatomic, copy) NSString *docid;
@property (nonatomic, copy) NSString *imageTitle;
@property (nonatomic, copy) NSString *url;
@property (nonatomic, retain) UIScrollView *changescrollView; //记录上一次的scrollView
@property (nonatomic, retain) NSMutableSet *recycledPages;
@property (nonatomic, retain) NSMutableSet *visiblePages;
@end

@implementation ImagesDetailController
- (NSMutableSet *)recycledPages {
    if (!_recycledPages) {
        self.recycledPages = [NSMutableSet set];
    }
    return _recycledPages;
}
- (NSMutableSet *)visiblePages {
    if (!_visiblePages) {
        self.visiblePages = [NSMutableSet set];
    }
    return _visiblePages;
}
- (NSMutableArray *)photosData {
    if (!_photosData) {
        self.photosData = [NSMutableArray array];
    }
    return [[_photosData retain] autorelease];
}
- (void)dealloc {
    [_recycledPages release];
    [_visiblePages release];
    [_url release];
    [_imageTitle release];
    [_changescrollView release];
    [_docid release];
    [_skipID release];
    [_skipTypeID release];
    [_photosData release];
    [super dealloc];
}




- (void)viewDidLoad {
    [super viewDidLoad];
    if (self.skipTypeID.length > 4) {
        self.skipTypeID =  [self.skipTypeID substringFromIndex:4];
    } else if (self.skipTypeID.length < 4) {
        return;
    }
    [self initUI];
    [self  getUrl];
    [self addGestureRecognizer];
}


#pragma mark -- 创建视图
-(void)initUI
{
     self.view.backgroundColor = [UIColor blackColor];
    self.detailView = [[ImageDetailView alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
    [self.view addSubview:self.detailView];
    [_detailView release];
   
    [self.detailView.btnBack addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.detailView.btnComment addTarget:self action:@selector(commentAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.detailView.btnSave addTarget:self action:@selector(saveAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.detailView.btnShare addTarget:self action:@selector(shareAction:) forControlEvents:UIControlEventTouchUpInside];
  

}



#pragma mark  -- 手势

-(void)addGestureRecognizer
{
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
    [self.detailView.imagesScrollView addGestureRecognizer:tap];
    [tap release];
    //双击手势，进入图片缩放界面
    UITapGestureRecognizer *twoTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTwoTap:)];
    twoTap.numberOfTapsRequired = 2;
    [self.detailView.imagesScrollView addGestureRecognizer:twoTap];
    [twoTap release];
    //解决单击双击手势并存问题
    [tap requireGestureRecognizerToFail:twoTap];
    
    //长按手势 ，用户保存图片到相册
    UILongPressGestureRecognizer *press = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handlePress:)];
    [self.detailView.imagesScrollView addGestureRecognizer:press];
    [press  release];
    
}

-(void)handleTap:(UITapGestureRecognizer *)tap
{
    if (_detailView.layerView.frame.origin.y < 0) {
        [UIView animateWithDuration:0.5 animations:^{
            [[UIApplication sharedApplication]  setStatusBarHidden:NO];
            _detailView.toolBar.frame = CGRectMake(0, self.view.frame.size.height - 40 * SCREEN_HEIGHT, 375 * SCREEN_WIDTH, 40 * SCREEN_HEIGHT);
            _detailView.layerView.frame = CGRectMake(0, 0, 375 * SCREEN_WIDTH, 100 * SCREEN_HEIGHT);
            _detailView.layerViewNote.frame = CGRectMake(0, self.view.frame.size.height - 170 * SCREEN_HEIGHT, 375 * SCREEN_WIDTH, 170 * SCREEN_HEIGHT);
        }];
    } else {
        [UIView animateWithDuration:0.5 animations:^{
            [[UIApplication sharedApplication]  setStatusBarHidden:YES];
            _detailView.toolBar.frame = CGRectMake(0, self.view.frame.size.height + 40 * SCREEN_HEIGHT, 375 * SCREEN_WIDTH, 40* SCREEN_HEIGHT);
            _detailView.layerView.frame = CGRectMake(10 * SCREEN_WIDTH, - 100 * SCREEN_HEIGHT , 375 * SCREEN_WIDTH, 100* SCREEN_HEIGHT);
            _detailView.layerViewNote.frame = CGRectMake(0, self.view.frame.size.height + 170* SCREEN_HEIGHT, 375 * SCREEN_WIDTH, 170* SCREEN_HEIGHT);
        }];
    }
   
}

- (void)handleTwoTap:(UITapGestureRecognizer *)twotap {
     self.modalTransitionStyle =  UIModalTransitionStyleCoverVertical;
    if (self.detailView.imagesScrollView.subviews.count) {
        self.changescrollView = [self.detailView.imagesScrollView subviews][0];
        [UIView animateWithDuration:0.5 animations:^{
            self.changescrollView .zoomScale =  self.changescrollView.zoomScale == 1.0 ? 2.0 : 1.0;
        }];
    }

}

- (void)handlePress:(UIGestureRecognizer *)press {
    //保存imageView上展示的图片到相册
    if (press.state == UIGestureRecognizerStateBegan) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"您确定要保存吗？" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
        [alert show];
        [alert release];
    }
}


//保存功能
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
   }

#pragma mark  -- action

-(void)backAction:(UIButton *)btn{

    self.navigationController.navigationBarHidden = NO;
    self.tabBarController.tabBar.hidden = NO;
    [self.navigationController popViewControllerAnimated:YES];
}



-(void)commentAction:(UIButton *)btn{
    CommentController *commentController = [[CommentController alloc] init];
    commentController.docid = self.docid; //传唯一标识
    commentController.flag = @"photoview_bbs"; //标识是图片集, 跳转评论标识
    
    [self setHidesBottomBarWhenPushed:YES];
    [self.navigationController pushViewController:commentController animated:YES];
    [self setHidesBottomBarWhenPushed:YES];
    [commentController release];
}
//收藏
-(void)saveAction:(UIButton *)btn{
    FavoriteModel *model = [[FavoriteModel alloc]init];
    model.fchtitle = self.imageTitle;
    model.skipTypeID = self.skipTypeID;
    model.skipID = self.skipID;
    model.flag = @"IMAGES";
    model.fchboardid = @"photoview_bbs";
    MBProgressHUD *hud = [[MBProgressHUD alloc]init];
    [self.view addSubview:hud];
    if ([DataHandle insertData:model ]) {
        hud.labelText = @"收藏成功";
    }else{
        hud.labelText = @"已经收藏";
    }
    
    hud.dimBackground = YES;
    hud.mode = MBProgressHUDModeText;
    [hud showAnimated:YES whileExecutingBlock:^{
        sleep(1);
    } completionBlock:^{
        [hud removeFromSuperview];
    }];
    [hud release];
    [model release];
}
-(void)shareAction:(UIButton *)btn{
    
    UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToSina];
    /**
     Sns平台类，用`platformName`作为标识，指定显示名称、显示的图片，点击之后的响应。
     */
    snsPlatform.displayName = @"新浪";
    snsPlatform.loginName = @"网易";
    
    
    UMSocialSnsPlatform *snsPlatform2 = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToTencent];
    snsPlatform2.displayName = @"腾讯微博";
    
    
    
    //分享第二步
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"558936d367e58eb81b001298"
                                      shareText:@"你要分享的文字"
                                     shareImage:[UIImage imageNamed:@"Icon-29.png"]
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent,UMShareToRenren,nil]
                                       delegate:nil];
    

    
    
    
}

-(void)getUrl {

   
    NetRequest *net = [[NetRequest alloc]init];
    [net GET:[ NSString stringWithFormat:@"http://c.3g.163.com/photo/api/set/%@/%@.json",self.skipTypeID, self.skipID] completion:^(id operation, id respObj, NSError *error) {
        
        NSMutableDictionary *dic = respObj;
        
        ImagesDetailModel *model = [[ImagesDetailModel alloc]init];
        
        [model setValuesForKeysWithDictionary:dic];
        self.detailView.model = model;
        self.docid = model.postid;
        self.imageTitle = model.setname;
        self.url = model.url;
          [self configureImageScrollView:model.photos];
        
    }];
 
}
#pragma mark - 视图布局
- (void)configureImageScrollView:(NSMutableArray *)photos {
    self.photosData = photos;
    _detailView.imagesScrollView.contentSize = CGSizeMake(photos.count * 375 * SCREEN_WIDTH, 0);
    _detailView.imagesScrollView.delegate = self;
    _detailView.imagesScrollView.pagingEnabled = YES;
    [self tilePages];
}

- (void)tilePages
{
    CGRect visibleBounds = _detailView.imagesScrollView.bounds;
    int firstNeededPageIndex = floorf(CGRectGetMinX(visibleBounds) / CGRectGetWidth(visibleBounds));
    int lastNeededPageIndex = floorf((CGRectGetMaxX(visibleBounds)-1) / CGRectGetWidth(visibleBounds));
    firstNeededPageIndex = MAX(firstNeededPageIndex, 0);
    lastNeededPageIndex = MIN(lastNeededPageIndex, (int)[self.photosData count] - 1);
    if (self.visiblePages) {
        
        for (IndexScrollView *page in self.visiblePages) {
            //不显⽰的判断条件
            if (page.index < firstNeededPageIndex || page.index > lastNeededPageIndex) {
                //将没有显示的ImageView保存在recycledPages里
                [self.recycledPages addObject:page];
                //将未显示的ImageView移除
                [page removeFromSuperview];
            }
        }
    }
    //集合-指定集合(即:所有不在既定集合中的元素)
    [self.visiblePages minusSet:self.recycledPages];
    
    while (self.recycledPages.count > 2) {
        [self.recycledPages removeObject:[self.recycledPages anyObject]];
    }
    // add missing pages
    for (int index = firstNeededPageIndex; index <= lastNeededPageIndex; index++) {
        if (![self isDisplayingPageForIndex:index]) { //当index对应的ImageView没有显示时,使用重用来定义ImageView
            IndexScrollView *page = [self dequeueRecycledPage]; //当page = = nil
            if (!page) {
                page = [[[IndexScrollView alloc] init] autorelease];
                page.bounces = YES;
                page.delegate = self;
                page.zoomScale = 1.0;
                page.minimumZoomScale = 1.0;
                page.maximumZoomScale = 2.0;
                page.showsVerticalScrollIndicator = NO;
                page.directionalLockEnabled = YES;
            }
            //设置index对应的ImageView图片和位置
            [self configurePage:page forIndex:index];
            //将page加入到visiblePages集合里
            [self.visiblePages addObject:page];
            [_detailView.imagesScrollView addSubview:page];
        }
    }
}



- (BOOL)isDisplayingPageForIndex:(NSUInteger)index {
    BOOL foundPage = NO;
    for (IndexScrollView *page in self.visiblePages) {
        if (page.index == index) { //如果index所对应的ImageView在可见数组中,将标志位标记为YES,否则返 回NO
            foundPage = YES;
            break;
        }
    }
    return foundPage;
}
- (void)configurePage:(IndexScrollView *)page forIndex:(NSUInteger)index {
    page.index = index; //这句要写，不然第一张会消失
    page.frame = CGRectMake(375 *SCREEN_WIDTH * index, -20 *SCREEN_HEIGHT,375 *SCREEN_WIDTH , 667 * SCREEN_HEIGHT);
    page.imageV.contentMode = UIViewContentModeScaleAspectFit;//自适应图片大小
    page.imageV.frame = self.view.bounds;
    [page.imageV sd_setImageWithURL: self.photosData[index][@"imgurl"] placeholderImage:[UIImage imageNamed:@"background"]];
}


- (IndexScrollView *)dequeueRecycledPage {
    //查看是否有重用对象
    IndexScrollView *page = [self.recycledPages anyObject];
    if (page) {
        [[page retain] autorelease];
        //返回重用对象,并从重用集合中删除
        [self.recycledPages removeObject:page];
    }
    return page;
}



#pragma mark - UIScrollViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [self tilePages];
}


//返回缩放的视图
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    return  [[scrollView subviews] firstObject];
}
//结束缩放时让imageView 居中
- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale{
    CGFloat offsetX = (scrollView.bounds.size.width > scrollView.contentSize.width)?(scrollView.bounds.size.width - scrollView.contentSize.width) * 0.5 : 0.0;
    CGFloat offsetY = (scrollView.bounds.size.height > scrollView.contentSize.height)?(scrollView.bounds.size.height - scrollView.contentSize.height) * 0.5 : 0.0;
    ((UIImageView *)[[scrollView subviews] firstObject]).center = CGPointMake(scrollView.contentSize.width * 0.5 + offsetX,scrollView.contentSize.height * 0.5 + offsetY);
}

//当滚动视图停⽌止
- (void)scrollViewDidEndDecelerating:(UIScrollView*)scrollView {
    NSInteger index = self.detailView.imagesScrollView.contentOffset.x / 375 * SCREEN_WIDTH;
    _detailView.note.text = [NSString stringWithFormat:@"%@",self.photosData[index][@"note"]];
    _detailView.page.text = [NSString stringWithFormat:@"%ld/%ld", (long)(index + 1), (unsigned long)self.photosData.count];
    //切换图片后，将变化的图片，变回原来的大小
    
        self.changescrollView.zoomScale = 1.0;
    
    self.changescrollView = [_detailView.imagesScrollView subviews][0];
  
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
